package com.example.showdemo;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.showdemo.controller.HandleController;
import com.example.showdemo.controller.IController;
import com.example.showdemo.model.HandleModel;
import com.example.showdemo.model.IModel;

public class MainActivity extends Activity implements IView {

    private IModel model = new HandleModel();
    private IController controller = new HandleController();

    private EditText edit;
    private Button clearText;
    private TextView msgText;
    private TextView titleText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit = (EditText)findViewById(R.id.edit);
        titleText = (TextView)findViewById(R.id.titleText);
        msgText = (TextView)findViewById(R.id.msgText);
        clearText = (Button)findViewById(R.id.clearText);
        titleText.setText("MVC");

        setController(controller);
        model.setView(this);
        controller.setModel(model);

        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                // 通知 Controller 输入的数据产生变化
                controller.onDataChanged(s.toString());
            }
        });
        clearText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                controller.clearData();
            }
        });
    }

    @Override
    public void setController(IController controller) {
        this.controller = controller;
    }

    @Override
    public void dataHanding() {
        msgText.setText("handle data ...");
    }

    @Override
    public void onDataHandled(String data) {
        if (TextUtils.isEmpty(data)) {
            edit.setText("");
            msgText.setText("default msg");
        } else {
            msgText.setText(data);
        }
    }
}


